package com.smartlib.cmnObject.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 16/6/24.
 * gson 解析的工具类
 */
public class GsonUtil {
    /***
     * string 转对象
     *
     * @param value
     * @param cla
     * @param <T>
     * @return
     */
    public static <T> T praseFromStringToBean(String value, Class<T> cla) {
        Gson gson = new Gson();
        T t = gson.fromJson(value, cla);
        return t;
    }

    /***
     * 对象转string
     *
     * @param object
     * @return
     */
    public static String parseFromBeanToString(Object object) {
        String value = "";
        Gson gson = new Gson();
        value = gson.toJson(object);
        return value;
    }
    public static <T> List<T> paraeFromStringToList(String value, Class<T> cla) {
        ArrayList<T> mList = new ArrayList<T>();
        Gson gson = new Gson();
        JsonArray array = new JsonParser().parse(value).getAsJsonArray();
        for (final JsonElement elem : array) {
            mList.add(gson.fromJson(elem, cla));
        }
        return mList;
    }

}
